import { App } from 'vue'
import {
  createRouter,
  createWebHashHistory,
  RouteRecordName,
  RouteRecordRaw
} from 'vue-router'
import { AppRouteRecordRaw } from './types'
import constantRoutes from './constantModules'
import store from '@/store'
import { PermissionMutationTypes } from '@/store/modules/permission'

export { constantRoutes }

// const importDynamicComp = (name) => {
//   return import('@/views').then(res => {
//     return res[name]['default']
//   })
// }

const asyncFiles = require.context('./permissionModules', true, /\.ts$/)
let permissionModules: Array<AppRouteRecordRaw> = []
console.log('asyncFiles', asyncFiles.keys())
asyncFiles.keys().forEach(key => {
  if (key === './index.ts') return
  permissionModules.push(...asyncFiles(key).default)
})
// 排序
permissionModules = permissionModules.sort(
  (a: AppRouteRecordRaw, b: AppRouteRecordRaw): number => {
    return (a.meta?.sort as number) - (b.meta?.sort as number)
  }
)

export const asyncRoutes = [...permissionModules]

const routes: Array<AppRouteRecordRaw> = [...constantRoutes]

const router = createRouter({
  history: createWebHashHistory(),
  routes: routes as RouteRecordRaw[]
})

// 添加动态路由
export function addRoutes(dynamicRoutes: RouteRecordRaw[]) {
  dynamicRoutes.forEach((route: RouteRecordRaw) => {
    router.addRoute(route)
  })
}

// 重置路由
export function resetRouter() {
  // location.reload()
  const routes = router.getRoutes()
  const constantRoutes_names: Array<RouteRecordName | undefined> =
    constantRoutes
      .filter(item => item.name)
      .map(item => item.name)

  routes.forEach(route => {
    if (!route.name) {
      return
    }

    // 移除动态添加的路由
    if (!constantRoutes_names.includes(route.name)) {
      router.removeRoute(route.name)
    }
  })
  store.commit(PermissionMutationTypes.RESET_ROUTES)
}

// setTimeout(() => {
//   resetRouter()
//   console.log('resetRouter')
// }, 10000)

export function setupRouter(app: App<Element>) {
  app.use(router)
}

export default router
